package com.miniot.base.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miniot.base.dto.TypeTwoTreeDTO;
import com.miniot.base.entity.BoundManage;
import com.miniot.base.entity.TypeOne;
import com.miniot.base.entity.TypeTwo;
import com.miniot.base.mapper.TypeOneMapper;
import com.miniot.base.mapper.TypeTwoMapper;
import com.miniot.base.service.BoundManageService;
import com.miniot.base.service.TypeTwoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 二级类型表
 *
 * @author zzq
 * @date 2023-10-17 11:16:07
 */
@Service
@AllArgsConstructor
@Slf4j
public class TypeTwoServiceImpl extends ServiceImpl<TypeTwoMapper, TypeTwo> implements TypeTwoService {

    private final BoundManageService boundManageService;
    private final TypeOneMapper typeOneMapper;
    @Override
    public boolean removeTypeTwoById(Long id) {
        //todo 有问题
        List<BoundManage> list = boundManageService.list(new LambdaQueryWrapper<BoundManage>().eq(BoundManage::getId, id));
        if (list.size()>0) {
            throw new RuntimeException("该类型正在使用,不可删除");
        }
        this.removeById(id);
        return true;
    }

    @Override
    public List<TypeTwoTreeDTO> getTree() {
        List<TypeOne> list = typeOneMapper.selectList(null);
        List<TypeTwoTreeDTO> data = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(list.size())) {
          list.forEach(m->{
              List<TypeTwo> list1 = this.list(new LambdaQueryWrapper<TypeTwo>().eq(TypeTwo::getTypeOneId, m.getId()));
              List<TypeTwoTreeDTO> child = new ArrayList<>();
              list1.forEach(l->{
                  child.add(TypeTwoTreeDTO.builder()
                          .typeCode(l.getTypeTwoCode())
                          .typeId(l.getId())
                          .typeName(l.getTypeTwoName())
                          .build());
              });
              data.add(TypeTwoTreeDTO.builder()
                      .typeCode(m.getTypeOneCode())
                      .typeId(m.getId())
                      .typeName(m.getTypeOneName())
                      .child(child)
                      .build());

          });
        }
        return data;
    }
}
